package com.sst.sysst.sdklib;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.iget.datareporter.DataReporter;
import com.iget.datareporter.IReport;
import com.sst.sysst.sdklib.tools.Propety;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class InitSstSdk {
    
    //初始化SDK 获取 AppID
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;

    private static String mAppkey;

    private static Timer mTimer;

    private static DataReporter mDataReporter;

    /**
     * 初始化
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:07
     */
    public static Boolean initWithAppKey(int flag, String appKey, Context context) {
        try {
            mContext = context;
            mAppkey = appKey;
            if (0 == flag) {
                Propety.setDomain("https://apibeta.shengshitong.com");
            } else {
                Propety.setDomain("https://shengstapi.tripln.top");
            }
            if (TextUtils.isEmpty(appKey)) {
                Log.e("InitSstSdk", "初始化失败: app_key不能为空");
                return false;
            } else {
                String certificationService = ReportingEvents.initServer(appKey, context);//初始化函数
                Log.e("InitSstSdk", certificationService);
                JSONObject jsct = new JSONObject(certificationService);
                int errcode = jsct.getInt("errcode");
                if (errcode == 0) {
                    initDatareporter(context);
                    SharedPreferences sp = context.getApplicationContext().getSharedPreferences("sst_sy_sdk", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("sst_flag", true);
                    editor.apply();
                    reportParms(context, appKey, 1, "", "", "app_in", 0, "");
                    mTimer = new Timer();
                    mTimer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            reportParms(context, appKey, 2, "", "", "app_hearbeat", 0, "");

                        }
                    }, 6000, 60000);
                    return true;
                } else {
                    Log.w("InitSstSdk::", "key验证失败");
                    SharedPreferences sp = context.getApplicationContext().getSharedPreferences("sst_sy_sdk", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("sst_flag", false);
                    editor.apply();
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //获取本地参数
    public static String reportParms(Context context, String appKey, int coldStart, String upperLevelPageUrl, String CurrentPageUrl, String event_id, int duration, String pageName) {
        try {
            String app_ver = AppUtils.getAppVersionCode() + "";//app版本号
            String os_ver = DeviceUtils.getSDKVersionCode() + "";//设备android版本号
            int os = 2;//1：iOS 2：android
            long ctime = TimeUtils.getNowMills();
            String phone_brand = DeviceUtils.getManufacturer();//设备商
            String phone_model = DeviceUtils.getModel();//设备型号
            String sdk_ver = AppUtils.getAppVersionCode() + "";
            String ip = "";
            String androidID = DeviceUtils.getAndroidID();//androidID
            String deviceId = DeviceUtils.getUniqueDeviceId();//imei
            String imei="";//imei
            String guid="";//唯一标识
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                imei=PhoneUtils.getIMEI();
            }
            if(TextUtils.isEmpty(imei)){
                guid=TextUtils.isEmpty(deviceId)?androidID:deviceId;
            }else{
                guid=imei;
            }
            String network = getNetworkType();//网络类型
            String ip_region = "";//ip属地
            String carrier = NetworkUtils.getNetworkOperatorName();//运营商
            String channel = "";//渠道
            String params = "{\"app_ver\":\"" + app_ver + "\",\"os_ver\":\"" + os_ver + "\",\"os\":\"" + os + "\",\"ctime\":\"" + ctime + "\",\"phone_brand\":\"" + phone_brand + "\"," +
                    "\"phone_model\":\"" + phone_model + "\",\"cold_start\":\"" + coldStart + "\",\"sdk_ver\":\"" + sdk_ver + "\",\"ip\":\"" + ip + "\",\"guid\":\"" + guid + "\",\"network\":\"" + network + "\"," +
                    "\"ip_region\":\"" + ip_region + "\",\"carrier\":\"" + carrier + "\",\"channel\":\"" + channel + "\",\"app_key\":\"" + appKey + "\",\"upper_level_page_url\":\"" + upperLevelPageUrl + "\",\"current_page_url\":\"" + CurrentPageUrl +
                    "\",\"mDuration\":\"" + duration + "\",\"mPageName\":\"" + pageName + "\",\"event_id\":\"" + event_id + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 关闭
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:08
     */
    public static void closeSstSdk(Context context, String appKey) {
        //取消数据上报，并且把上报对象置空，防止释放之后再次被调用出现crash
        DataReporter.releaseDataReporter(mDataReporter);
        mDataReporter = null;
        if (null != mTimer) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    /**
     * 上传页面信息数据
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:08
     */
    public static void updatePageInfo(Context context, String appKey, String eventId, String pageName, String upper_level_page_url, String current_page_url) {
        reportParms(context, appKey, 2, upper_level_page_url, current_page_url, "page_in", 0, "");
    }

    /**
     * 当页面展示时上传数据
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:08
     */
    public static void updatePageInfoByIsInVisible(Context context, String appKey, String eventId, String pageName, int duration, String upper_level_page_url, String current_page_url) {
        reportParms(context, appKey, 2, upper_level_page_url, current_page_url, "page_out", duration, pageName);
    }

    /**
     * 上传页面信息
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:09
     */
    public static void updatePageShowInfo(Context context, String appKey, String eventId, String pageName, int duration, String upper_level_page_url, String current_page_url) {
        reportParms(context, appKey, 2, upper_level_page_url, current_page_url, "page_show_time", duration, pageName);
    }

    /**
     * 获取网络状态
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:09
     */
    public static String getNetworkType() {
        String network1 = NetworkUtils.getNetworkType() + "";
        switch (network1) {
            case "NETWORK_WIFI":
                return "6";
            case "NETWORK_2G":
                return "1";
            case "NETWORK_3G":
                return "2";
            case "NETWORK_4G":
                return "3";
            default:
                return "";
        }
    }

    /**
     * 初始化上传工具
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:09
     */
    public static void initDatareporter(Context context) {
        final ReportImp reportImp = new ReportImp();
        mDataReporter = DataReporter.makeDataReporter("test", context.getFilesDir().getPath(), "testKey", reportImp);
        reportImp.setDataReporter(mDataReporter);
        //设置单次上报最大条数
        mDataReporter.setReportCount(10);
        //设置过期时间，0为不过期，多久的数据都上报，单位为秒
        mDataReporter.setExpiredTime(0);
        //设置上报间隔，1000表示 1秒报一次，单位毫秒
        mDataReporter.setReportingInterval(60 * 1000);
        //设置最大缓存大小 20k
        mDataReporter.setFileMaxSize(15 * 1024);
        //设置上报出错重试间隔，5代表上报出错后5秒后重试，如果再次上报失败，重试时间加5秒，也就是10秒。以此类推。单位秒。
        //如果设置为0，表示出错后立即上报，容易导致上报风暴，服务器打垮
        mDataReporter.setRetryInterval(15);
        mDataReporter.start();
        Log.w("InitSstSdk::", "InitSstSdk初始化成功");
    }

    /**
     * 检查网络连接
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:10
     */
    public static boolean checkNet(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.isConnected()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 网络监听
     *
     * @author:Create By LiBoRui
     * @createTime:2023/5/11 11:10
     */
    static class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (checkNet(context)) {
                //网络状态好时 重新唤起下DataReporter
                if (mDataReporter == null) {
                    return;
                }
                mDataReporter.reaWaken();
            }
        }
    }

    static class ReportImp implements IReport {
        private DataReporter mDataReporter;
        private Handler mUiHandler = new Handler(Looper.getMainLooper());

        public ReportImp() {
        }

        public void setDataReporter(DataReporter dataReporter) {
            mDataReporter = dataReporter;
        }

        @Override
        public void upload(final long key, final byte[][] data) {

            mUiHandler.postDelayed(() -> {
                if (mDataReporter == null) {
                    return;
                }
                String str = "";
                for (int i = 0; i < data.length; i++) {
                    if (i == data.length - 1) {
                        str += new String(data[i]);
                    } else {
                        str += new String(data[i]) + ",";
                    }
                }
                ReportingEvents.report(mContext, mAppkey, str, strs -> {
                    Log.w("strs:", strs);
                    try {
                        JSONObject jsct = new JSONObject(strs);
                        int errcode = jsct.getInt("errcode");
                        if (errcode == 0) {
                            mDataReporter.uploadSucess(key);
                            Log.w("mDataReporter", "success");
                        } else {
                            mDataReporter.uploadFailed(key);
                            Log.w("mDataReporter", "fail");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.w("mDataReporter", "fail");
                    }
                });
            }, 100);
        }
    }


    //--获取登录类型
    public static String updateLoginType(Context context, int loginType, String appKey) {
        try {
            int login_type = loginType;
            String params = "{\"login_type\":\"" + login_type + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--打开方式
    public static String updateCallFrom(Context context, String call_from, String appKey) {
        try {
            String params = "{\"call_from\":\"" + call_from + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--qq登录的openid
    public static String updateOpenIdForQQ(Context context, String qq_open_id, String appKey) {
        try {
            String params = "{\"qq_open_id\":\"" + qq_open_id + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--微信登录的openid
    public static String updateOpenIdForWx(Context context, String wx_open_id, String appKey) {
        try {
            String params = "{\"wx_open_id\":\"" + wx_open_id + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--支付宝登录的openid
    public static String updateOpenIdForAli(Context context, String alipay_open_id, String appKey) {
        try {
            String params = "{\"alipay_open_id\":\"" + alipay_open_id + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--手机号登录账号
    public static String updatePhoneNumber(Context context, String phone_number, String appKey) {
        try {
            String params = "{\"phone_number\":\"" + phone_number + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //--提供接口给宿主，可以放宿主自定义的公参
    @SuppressLint("LongLogTag")
    public static String updateBussinessParams(Context context, String business_params, String appKey) {
        try {
            String params = "{\"business_params\":\"" + business_params + "\"}";
            Log.w("InitSstSdk::", params);
            mDataReporter.push(params.getBytes());
            return "本地保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
